/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.queueservice;

import cn.ac.iie.di.wx.vo.PicUrlVo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class WriteTofile implements Runnable {

    public String filePath;
    public String fileName;
    public String list;
    public String preList;
    public LinkedBlockingQueue<PicUrlVo> picUrlBlockingQueue;
    public int number;
    public static Logger logger = Logger.getLogger(WriteTofile.class.getName());

    public WriteTofile(String filePath, String fileName, LinkedBlockingQueue<PicUrlVo> picUrlBlockingQueue) {
        this.filePath = filePath;
        this.fileName = fileName;
        this.picUrlBlockingQueue = picUrlBlockingQueue;
    }

    public WriteTofile(String filePath, String fileName, String list, String preList, LinkedBlockingQueue<PicUrlVo> picUrlBlockingQueue, int number) {
        this.filePath = filePath;
        this.fileName = fileName;
        this.list = list;
        this.preList = preList;
        this.picUrlBlockingQueue = picUrlBlockingQueue;
        this.number = number;
    }

    public WriteTofile(String filePath, String fileName, String list, LinkedBlockingQueue<PicUrlVo> picUrlBlockingQueue) {
        this.filePath = filePath;
        this.fileName = fileName;
        this.list = list;
        this.picUrlBlockingQueue = picUrlBlockingQueue;
    }

    public WriteTofile(String filePath, String fileName, String list, String preList, LinkedBlockingQueue<PicUrlVo> picUrlBlockingQueue) {
        this.filePath = filePath;
        this.fileName = fileName;
        this.list = list;
        this.preList = preList;
        this.picUrlBlockingQueue = picUrlBlockingQueue;
    }

    @Override
    public void run() {
        //创建指定路径
        while (true) {

            File f = new File(filePath);
            if (!f.exists() || !f.isDirectory()) {
                f.mkdirs();
            }
            //创建指定
            File file = new File(filePath + fileName);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException ex) {
                    logger.info(ex.getMessage(), ex);
                }
            }

            if (file.canWrite()) {
                //将路径写入文件夹
                PicUrlVo vo;
                for (int i = 0; i < 50; i++) {
                    try {
                        vo = picUrlBlockingQueue.poll(100, TimeUnit.MILLISECONDS);
//                    vo = new PicUrlVo("hh/adsa/ra" + number + ".jpg");

                        if (vo != null) {
                            list +=vo.getIsExist()+";"+ vo.getUrl() + "\r\n";
                            logger.info(vo.getUrl());
                        }

                        vo = null;
                    } catch (InterruptedException ex) {
                        logger.info(ex.getMessage(), ex);
                    }
                }
//                logger.info("list is finished");
                //若有数据则进行读写文件
                if (!list.equals("")) {
                    FileOutputStream outputStream = null;
//                    logger.info("preList " + preList + "\t" + "list " + list);
                    try {
                        InputStream responseIn = new FileInputStream(file);
                        Reader reader = new InputStreamReader(responseIn);
                        BufferedReader bufferedReader = new BufferedReader(reader);
                        String text = null;
                        StringBuffer stringBuffer = new StringBuffer();
                        while ((text = bufferedReader.readLine()) != null) {
                            stringBuffer.append(text + "\r\n");
                        }

                        //如果相等，则未被读取掉
                        if (preList.equals(stringBuffer.toString())) {
//                            logger.info(true);
                            outputStream = new FileOutputStream(file, true);
                        } else {
                            outputStream = new FileOutputStream(file);
                        }
                        String fileList = "";

                        Writer writer = new OutputStreamWriter(outputStream, "UTF-8");
                        writer.write(list);
                        writer.flush();
                        writer.close();
                        outputStream.close();
                        preList = list;
                        list = "";
//                        logger.info("preList " + preList + "\t" + "list " + list);
                        Thread.sleep(200);
                    } catch (FileNotFoundException ex) {
                        logger.info(ex.getMessage(), ex);
                    } catch (IOException ex) {
                        logger.info(ex.getMessage(), ex);
                    } catch (InterruptedException ex) {
                        logger.info(ex.getMessage(), ex);
                    } finally {

                    }
                }

            }
            f = null;
            file = null;
        }
    }
//
//    public static void main(String[] args) {
//        LinkedBlockingQueue<PicUrlVo> picUrlBlockingQueue = new LinkedBlockingQueue<>(100);
//        WriteTofile tofile = new WriteTofile("/home/jr/path/url/", "text.txt", "", "", picUrlBlockingQueue, 0);
//        Thread thread = new Thread(tofile);
//        thread.start();
//        logger.info("start test file");
//    }
//    public static void main(String[] args) throws InterruptedException, REConnectionException, RESessionException {
//        LinkedBlockingQueue<PicUrlVo> picUrlBlockingQueue = new LinkedBlockingQueue<>(100);
////        WriteTofile tofile = new WriteTofile("D:/path/url/", "url.txt", picUrlBlockingQueue);
////        Thread thread=new Thread(tofile);
////        thread.start();
//        REConnection conn = new REConnection("10.136.64.28:9877;10.136.64.29:9877;10.136.64.30:9877;10.136.64.31:9877;10.136.64.32:9877");
//
//        //生成builder，参数为topic，由具体业务决定
//        RESendSessionBuilder builder = (RESendSessionBuilder) conn.getSendSessionBuilder("rongreatest2_mq");
//        //设置数据结构，参数为每一列的列名、列类型、是否可以为空。注意： 如果设置为不能为空，那么如果添加数据时没有添加该列数据，会报错。
//        builder.addColumn("url", REFieldType.String, true);
//        RESendSession session = (RESendSession) builder.build();
//        session.start();
//        SendToQueueThread demo = new SendToQueueThread("10.136.64.28:9877;10.136.64.29:9877;10.136.64.30:9877;10.136.64.31:9877;10.136.64.32:9877",
//                "rongreatest2_mq", session, "rongrea_test_session", "url", picUrlBlockingQueue);
//        Thread t = new Thread(demo);
//        t.start();
//        int num = 1;
//        while (true) {
//            picUrlBlockingQueue.add(new PicUrlVo("test" + num + ".jpg"));
//            Thread.sleep(100);
//            ++num;
//        }
//    }
}
